package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code16ProductOfArrayExceptSelf {

    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];

        // 从左到右, 除当前元素的乘积, 即前缀积
        int tmp = 1;
        for (int i = 0; i < n; i++) {
            res[i] = tmp;
            tmp *= nums[i];
        }
        // 从右到左, 除当前元素的乘积, 即后缀积
        tmp = 1;
        for (int i = n - 1; i >= 0; i--) {
            res[i] *= tmp;
            tmp *= nums[i];
        }

        return res;
    }
}
